package com.lsa.letcode.the29.divide;

public class Solution {
    public int divide(int dividend, int divisor) {
    	if (divisor == 0) {
    		return Integer.MAX_VALUE;
    	}
    	else if (dividend == 0) {
    		return 0;
    	}
    	
    	int signum = signum(dividend, divisor);
    	if (dividend > 0) {
    		dividend = -dividend;
    	}
    	if (divisor > 0) {
    		divisor = -divisor;
    	}
    	
    	if (dividend > divisor) {
    		return 0;
    	}
    	
    	int res = 1;
    	int acc = divisor;
    	
    	try{
    		while(dividend <= add(acc, acc)) {
				res += res;
				acc = add(acc, acc);
			}
			
			while(dividend <= add(acc, divisor)) {
				res += 1;
				acc = add(acc, divisor);
			}
    	}
    	catch(ArithmeticException e) {
    		return Integer.MAX_VALUE;
    	}
    	
    	return signum > 0? res : -res;
    }
    
    private int signum(int dividend, int divisor) {
    	if (dividend > 0 && divisor < 0) {
    		return -1;
    	}
    	else if (dividend < 0 && divisor > 0) {
    		return -1;
    	}
		return 1;
	}

	private static int add(int a, int b) {
    	boolean isOverflow = false;
    	if (((a > 0 && b > 0) && a > Integer.MAX_VALUE - b) || ((a < 0 && b < 0) && a < Integer.MIN_VALUE - b)) {
			isOverflow = true;
		}
    	
    	if (isOverflow) {
    		throw new ArithmeticException();
    	}
    	
    	return a + b;
    }
}